package com.erp.erp_ui.Customer2Contact;

import com.erp.erp_entitys.Customer2Contact.Customer2ContactEntity;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactExample;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactVoEntity;
import com.erp.erp_entitys.Customer2Log.Customer2LogEntity;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Customer2.ICustomer2Service;
import com.erp.erp_servers.Customer2Contact.ICustomer2ContactService;
import com.erp.erp_servers.Customer2Log.ICustomer2LogService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客户联系人
 * @ClassName CustomerContactControl
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-07-03 23:07
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "customer2contact")
public class Customer2ContactControl extends Base {
    @Autowired
    ICustomer2ContactService customerContactService;
    @Autowired
    ICustomer2Service customerService;
    @Autowired
    ICustomer2LogService customerLogService;

    /**
     * 分页查询
     * @param
     * @return
     */
    @RequestMapping(value = "selectByPage")
    @ResponseBody
    public R<List<Customer2ContactVoEntity>> selectByPage(String company){
        try{
            //UserEntity user = (UserEntity)this.getBean("user");
           // String name=user.getName();
           // List<CustomerContactVoEntity> list=new ArrayList<CustomerContactVoEntity>();
           // CustomerContactExample example=new CustomerContactExample();
            //CustomerContactExample.Criteria criteria = example.createCriteria();
            List<Customer2ContactVoEntity> customerContactEntities=new ArrayList<Customer2ContactVoEntity>();
            if(!company.equals("")){
               // criteria.andCompanyEqualTo(company);
                 customerContactEntities = customerContactService.query(company);//customerContactService.selectByExample(example);
                /*for(int i=0;i<customerContactEntities.size();i++){
                    CustomerContactVoEntity vo=new CustomerContactVoEntity();
                    vo.convet(customerContactEntities.get(i));
                    list.add(vo);
                }*/
            }
            return R.build(customerContactEntities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取联系人信息
     *
     * @param company 供应商编码
     * @return 联系人信息
     */
    @RequestMapping(value = "getContactPerson")
    @ResponseBody
    public R<List<Customer2ContactVoEntity>> getContactPerson(String company) {
        try {
            List<Customer2ContactVoEntity> customerContactEntities = new ArrayList<>();
            if (StringUtils.isEmpty(company)) {
                return R.build(customerContactEntities);
            }
            customerContactEntities = customerContactService.query(company);
            return R.build(customerContactEntities);
        } catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 分页查询
     * @param
     * @return
     */
    @RequestMapping(value = "select2ByPage")
    @ResponseBody
    public R<List<Customer2ContactVoEntity>> select2ByPage(String company,String name,String email){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            // String name=user.getName();
           /* List<CustomerContactVoEntity> list=new ArrayList<>();
            List<String> list_comp=new ArrayList<String>();
            if(company.equals("")){
               // return R.build(list);
                CustomerExample example=new CustomerExample();
                CustomerExample.Criteria criteria = example.createCriteria();
                criteria.andSalesmanLike("%"+user.getCode()+"%");
                List<CustomerEntity> customerEntities = customerService.selectByExample(example);
                for(int i=0;i<customerEntities.size();i++){
                    list_comp.add(customerEntities.get(i).getCode());
                }
            }else{
                list_comp.add(company);
            }
            if(list_comp.size()==0){
                return R.build(list);
            }*/
           /* CustomerContactExample example=new CustomerContactExample();
            CustomerContactExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike("%"+name+"%");
            criteria.andEmailLike("%"+email+"%");*/
           // criteria.andCompanyIn(list_comp);
            //criteria.andSalesmanLike("%"+user.getCode()+"%");
           // List<CustomerContactEntity> customerContactEntities = customerContactService.selectByExample(example);
           /* for(int i=0;i<customerContactEntities.size();i++){
                CustomerContactVoEntity vo=new CustomerContactVoEntity();
                vo.convet(customerContactEntities.get(i));
                list.add(vo);
            }*/
            List<Customer2ContactVoEntity> query = customerContactService.query(name, email, user.getCustomerRole());
            return R.build(query);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> delete(String[] ids){
        try {
            List<Integer> list=new ArrayList<>();

            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
            }
            Customer2ContactExample example=new Customer2ContactExample();
            Customer2ContactExample.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            List<Customer2ContactEntity> customerContactEntities = customerContactService.selectByExample(example);
            Integer num = customerContactService.deleteByExample2(example,customerContactEntities);
//日志
            UserEntity user = (UserEntity)this.getBean("user");

            String codes="";
            for(int i=0;i<customerContactEntities.size();i++){
                codes+=customerContactEntities.get(i).getCompany()+",";
            }
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(codes);
            log.setType("删除");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("联系人所属客户编码："+codes);
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据id获取联系人
     * @param id
     * @return
     */
    @RequestMapping(value = "queryByid",method = RequestMethod.POST)
    @ResponseBody
    public R<List<Customer2ContactVoEntity>> queryByid(Integer id){
        try {
            List<Customer2ContactVoEntity> list=new ArrayList<>();
            Customer2ContactExample example=new Customer2ContactExample();
            Customer2ContactExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(id);
            List<Customer2ContactEntity> customerContactEntities = customerContactService.selectByExample(example);
            for(int i=0;i<customerContactEntities.size();i++){
                Customer2ContactVoEntity vo=new Customer2ContactVoEntity();
                vo.convet(customerContactEntities.get(i));
                list.add(vo);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "insert",method = RequestMethod.POST)
    @ResponseBody
    public  R insert(@RequestBody Customer2ContactEntity recode){
        try {

            if(recode.getId() != null){//id存在就更新
                //选择了关联供应商之后就不用检测邮件是否重复
                if (StringUtils.isEmpty(recode.getRelevancyCusCode())){
                    String flag=isRepeat(recode.getId(),recode.getEmail(),2);
                    switch (flag){
                        case "email":
                            return R.buildCustomize(-100001,"联系人邮箱地址重复");
                    }
                }
               customerContactService.updateByPrimaryKeySelective(recode);
            }else{
                if (StringUtils.isEmpty(recode.getRelevancyCusCode())){
                    String flag=isRepeat(null,recode.getEmail(),1);
                    switch (flag){
                        case "email":
                            return R.buildCustomize(-100001,"联系人邮箱地址重复");
                    }
                }


                customerContactService.insertSelective(recode);
            }

            //日志
            UserEntity user = (UserEntity)this.getBean("user");
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(recode.getCompany());
            log.setType("新增");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("联系人所属客户编码："+recode.getCompany());
            customerLogService.insert(log);
            return R.build(ResultStatusEnum.SUCCESS);

        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 检测 邮箱地址 是否重复
     * @param type 1：新增 2：修改
     * @return
     */
    private String isRepeat(Integer id,String email,Integer type){
        if (StringUtils.isNotEmpty(email)){
            Customer2ContactExample example=new Customer2ContactExample();
            Customer2ContactExample.Criteria criteria=example.createCriteria();
            criteria.andEmailEqualTo(email);
            List<Customer2ContactEntity> entities = customerContactService.selectByExample(example);
            if (entities.size() > 0) {
                if (type == 1) {
                    return "email";
                }
                if (type == 2) {
                    for (Customer2ContactEntity p : entities) {
                        if (!p.getId().equals(id) ) {
                            return "email";
                        }
                    }
                }
            }

        }
        return "";
    }


}
